package com.hy.service;

import com.hy.AppHttpCodeEnum;
import com.hy.Result.ResponseResult;
import com.hy.mapper.CartItemMapper;
import com.hy.mapper.MedicineBasicInfoMapper;
import com.hy.medicine.CartItem;
import com.hy.medicine.MedicineBasicInfo;
import com.hy.medicine.dingdan.vo.CartItemAddVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车服务实现类
 */
@Service
public class CartItemServiceImpl implements CartItemService {

    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private MedicineBasicInfoMapper medicineBasicInfoMapper;

    /**
     * 添加商品到购物车
     * @param cartItemAddVO 购物车添加VO
     * @param userId 用户ID
     * @return 响应结果
     */
    @Override
    @Transactional
    public ResponseResult addToCart(CartItemAddVO cartItemAddVO, Long userId) {
        // 校验参数
        if (cartItemAddVO.getMedicineId() == null || cartItemAddVO.getQuantity() == null || cartItemAddVO.getQuantity() <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 查询药品信息
        MedicineBasicInfo medicine = medicineBasicInfoMapper.selectById(cartItemAddVO.getMedicineId());
        if (medicine == null || medicine.getDeleted() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "药品不存在");
        }

        // 检查库存
        if (medicine.getMinStock() < cartItemAddVO.getQuantity()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.STOCK_NOT_ENOUGH, "库存不足，当前库存：" + medicine.getMinStock());
        }

        // 查询是否已存在购物车
        CartItem existItem = cartItemMapper.selectByUserIdAndMedicineId(userId, cartItemAddVO.getMedicineId().longValue());

        if (existItem != null) {
            // 更新数量
            int newQuantity = existItem.getQuantity() + cartItemAddVO.getQuantity();

            // 再次检查库存
            if (medicine.getMinStock() < newQuantity) {
                return ResponseResult.errorResult(AppHttpCodeEnum.STOCK_NOT_ENOUGH, "库存不足，当前库存：" + medicine.getMinStock());
            }

            existItem.setQuantity(newQuantity);
            existItem.setUpdateTime(LocalDateTime.now());
            cartItemMapper.updateById(existItem);
        } else {
            // 创建新的购物车项
            CartItem cartItem = new CartItem();
            cartItem.setUserId(userId);
            cartItem.setMedicineId(cartItemAddVO.getMedicineId().longValue());
            cartItem.setMedicineName(medicine.getMedicineName());
            cartItem.setImageUrl(medicine.getImageUrl());
            cartItem.setSpecification(medicine.getSpecification());
            cartItem.setDosageForm(medicine.getDosageForm());
            cartItem.setPrice(medicine.getPrice());
            cartItem.setQuantity(cartItemAddVO.getQuantity());
            cartItem.setCreateTime(LocalDateTime.now());
            cartItem.setUpdateTime(LocalDateTime.now());

            cartItemMapper.insert(cartItem);
        }

        return ResponseResult.okResult();
    }

    /**
     * 获取购物车列表
     * @param userId 用户ID
     * @return 购物车列表
     */
    @Override
    public ResponseResult getCartList(Long userId) {
        List<CartItem> cartItems = cartItemMapper.selectByUserId(userId);
        return ResponseResult.okResult(cartItems);
    }

    /**
     * 更新购物车商品数量
     * @param id 购物车项ID
     * @param quantity 数量
     * @param userId 用户ID
     * @return 响应结果
     */
    @Override
    @Transactional
    public ResponseResult updateCartItemQuantity(Long id, Integer quantity, Long userId) {
        // 校验参数
        if (id == null || quantity == null || quantity <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 查询购物车项
        CartItem cartItem = cartItemMapper.selectById(id);
        if (cartItem == null || !cartItem.getUserId().equals(userId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "购物车项不存在");
        }

        // 查询药品信息
        MedicineBasicInfo medicine = medicineBasicInfoMapper.selectById(cartItem.getMedicineId());
        if (medicine == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "药品不存在");
        }

        // 检查库存
        if (medicine.getMinStock() < quantity) {
            return ResponseResult.errorResult(AppHttpCodeEnum.STOCK_NOT_ENOUGH, "库存不足，当前库存：" + medicine.getMinStock());
        }

        // 更新数量
        cartItem.setQuantity(quantity);
        cartItem.setUpdateTime(LocalDateTime.now());
        cartItemMapper.updateById(cartItem);

        return ResponseResult.okResult();
    }

    /**
     * 删除购物车商品
     * @param id 购物车项ID
     * @param userId 用户ID
     * @return 响应结果
     */
    @Override
    @Transactional
    public ResponseResult deleteCartItem(Long id, Long userId) {
        // 校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 查询购物车项
        CartItem cartItem = cartItemMapper.selectById(id);
        if (cartItem == null || !cartItem.getUserId().equals(userId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "购物车项不存在");
        }

        // 删除购物车项
        cartItemMapper.deleteById(id);

        return ResponseResult.okResult();
    }

    /**
     * 清空购物车
     * @param userId 用户ID
     * @return 响应结果
     */
    @Override
    @Transactional
    public ResponseResult clearCart(Long userId) {
        cartItemMapper.deleteByUserId(userId);
        return ResponseResult.okResult();
    }

    /**
     * 获取购物车商品数量
     * @param userId 用户ID
     * @return 购物车商品数量
     */
    @Override
    public ResponseResult getCartCount(Long userId) {
        int count = cartItemMapper.countByUserId(userId);
        return ResponseResult.okResult(count);
    }
}
